package com.phoenix.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.phoenix.entity.*;
import com.phoenix.service.GroupChampionshipService;
import com.phoenix.service.MemberChampionshipService;
import com.phoenix.service.UserService;
import com.phoenix.util.ExcelUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/championship")
public class ChampionshipController {
    @Autowired
    GroupChampionshipService groupChampionshipService;
    @Autowired
    MemberChampionshipService memberChampionshipService;
    @Autowired
    UserService userService;

    //单项赛
    @GetMapping("/memberChampionshipList")
    public String memberChampionshipList(Model model, @RequestParam(value = "keywords", defaultValue = "") String keywords, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        //进行分页，提供关键字查询
        //pageSize为分页的行数
        Map<String, Object> search = new HashMap<>();
        search.put("keywords", keywords);
        //使用PageHelper包装数据
        Subject currentUser = SecurityUtils.getSubject();
        String userName = (String) currentUser.getPrincipal();
        Users user = userService.selectUserByUsername(userName);
        PageHelper.startPage(pageNum, pageSize);
        List<MemberChampionship> list;
        if (user.getRole().equals("admin")) {
            list = memberChampionshipService.selectNSearch(search);
        } else {
            search.put("userID", user.getUserID());
            list = memberChampionshipService.selectNSearchForUser(search);
        }
        PageInfo<MemberChampionship> pageInfo = new PageInfo<>(list);
        model.addAttribute("result", new ResponseData<>(200, "ok", pageInfo));
        model.addAttribute("keywords", keywords);

        return "championships/memberChampionshipsList";
    }

    @PostMapping("/addMemberChampionship")
    public String addMemberChampionship(Model model, MemberChampionship memberChampionship) {
        Subject currentUser = SecurityUtils.getSubject();
        String userName = (String) currentUser.getPrincipal();
        Users user = userService.selectUserByUsername(userName);
        memberChampionship.setUserID(user.getUserID());
        Boolean addMemberChampionship = memberChampionshipService.addMemberChampionship(memberChampionship);
        if (addMemberChampionship) {
            model.addAttribute("msg", "上传成功！");
        } else {
            model.addAttribute("msg", "上传失败！");
        }
        return "championships/memberChampionships";
    }

    @DeleteMapping("/deleteMemberChampionship")
    @ResponseBody
    public ResponseData<String> deleteMemberChampionship(@RequestParam String ID) {
        //Some Magic.
        String[] IDS = ID.split(",");
        List<String> IDList = Arrays.asList(IDS);
        Boolean test = memberChampionshipService.memberChampionshipDelete(IDList);
        if (test) {
            return new ResponseData<>(200, "删除成功！", null);
        } else {
            return new ResponseData<>(500, "删除失败！", null);
        }
    }

    @DeleteMapping("/delMC/{ID}")
    @ResponseBody
    public ResponseData<String> delMC(@PathVariable String ID) {
        Boolean test = memberChampionshipService.memberChampionshipDeleteSingle(ID);
        if (test) {
            return new ResponseData<>(200, "删除成功！", null);
        } else {
            return new ResponseData<>(500, "删除失败！", null);
        }
    }

    @GetMapping("/memberChampionshipEditPage")
    public String memberChampionshipEditPage(Model model, Integer ID) {
        MemberChampionship memberChampionship = memberChampionshipService.getMemberChampionshipByID(ID);
        model.addAttribute("memberChampionship", memberChampionship);
        model.addAttribute("method", "put");
        return "championships/memberChampionships";
    }

    @PutMapping("/addMemberChampionship")
    public String memberChampionshipEdit(Model model, MemberChampionship memberChampionship) throws InterruptedException {
        model.addAttribute("memberChampionship", memberChampionship);
        if (memberChampionshipService.updateMemberChampionship(memberChampionship)) {
            model.addAttribute("msg", "更新成功!");
        } else {
            model.addAttribute("msg", "更新失败!");
            wait(1000);
            return "championships/memberChampionshipsList";
        }
        model.addAttribute("method", "put");
        return "championships/memberChampionships";
    }

    @RequestMapping("/exportMemberChampionship/{ID}")
    @ResponseBody
    public void exportMemberChampionship(@PathVariable Integer ID) throws IOException {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = null;
        if (attr != null) {
            response = attr.getResponse();
        }
        MemberChampionship memberChampionship = memberChampionshipService.getMemberChampionshipByID(ID);
        ExcelUtil excelUtil = new ExcelUtil();
        if (response != null) {
            excelUtil.exportForMember(response, memberChampionship);
        }
    }

    //团体赛
    @GetMapping("/groupChampionshipList")
    public String groupChampionshipList(Model model, @RequestParam(value = "keywords", defaultValue = "") String keywords, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        //进行分页，提供关键字查询
        //pageSize为分页的行数
        Map<String, Object> search = new HashMap<>();
        search.put("keywords", keywords);
        Subject currentUser = SecurityUtils.getSubject();
        String userName = (String) currentUser.getPrincipal();
        Users user = userService.selectUserByUsername(userName);
        PageHelper.startPage(pageNum, pageSize);
        //使用PageHelper包装数据
        List<GroupChampionship> list;
        if (user.getRole().equals("admin")) {
            list = groupChampionshipService.selectNSearch(search);
        } else {
            search.put("userID", user.getUserID());
            list = groupChampionshipService.selectNSearchForUser(search);
        }
        PageInfo<GroupChampionship> pageInfo = new PageInfo<>(list);
        model.addAttribute("result", new ResponseData<>(200, "ok", pageInfo));
        model.addAttribute("keywords", keywords);
        return "championships/groupChampionshipsList";
    }

    @PostMapping("/addGroupChampionship")
    public String addMemberChampionship(Model model, GroupChampionship groupChampionship) {
        Subject currentUser = SecurityUtils.getSubject();
        String userName = (String) currentUser.getPrincipal();
        Users user = userService.selectUserByUsername(userName);
        groupChampionship.setUserID(user.getUserID());
        Boolean addMemberChampionship = groupChampionshipService.addGroupChampionship(groupChampionship);
        if (addMemberChampionship) {
            model.addAttribute("msg", "上传成功！");
        } else {
            model.addAttribute("msg", "上传失败！");
        }
        return "championships/groupChampionships";
    }

    @DeleteMapping("/deleteGroupChampionship")
    @ResponseBody
    public ResponseData<String> adminDel(@RequestParam String ID) {
        //Some Magic.
        String[] IDS = ID.split(",");
        List<String> IDList = Arrays.asList(IDS);
        Boolean test = groupChampionshipService.groupChampionshipDelete(IDList);
        if (test) {
            return new ResponseData<>(200, "删除成功！", null);
        } else {
            return new ResponseData<>(500, "删除失败！", null);
        }
    }

    @DeleteMapping("/delGC/{ID}")
    @ResponseBody
    public ResponseData<String> delGC(@PathVariable String ID) {
        Boolean test = groupChampionshipService.groupChampionshipDeleteSingle(ID);
        if (test) {
            return new ResponseData<>(200, "删除成功！", null);
        } else {
            return new ResponseData<>(500, "删除失败！", null);
        }
    }

    @GetMapping("/groupChampionshipEditPage")
    public String groupChampionshipEditPage(Model model, Integer ID) {
        GroupChampionship groupChampionship = groupChampionshipService.getGroupChampionshipByID(ID);
        model.addAttribute("groupChampionship", groupChampionship);
        model.addAttribute("method", "put");
        return "championships/groupChampionships";
    }

    @PutMapping("/addGroupChampionship")
    public String groupChampionshipEdit(Model model, GroupChampionship groupChampionship) throws InterruptedException {
        model.addAttribute("groupChampionship", groupChampionship);
        if (groupChampionshipService.updateGroupChampionship(groupChampionship)) {
            model.addAttribute("msg", "更新成功!");
        } else {
            model.addAttribute("msg", "更新失败!");
            wait(1000);
            return "championships/groupChampionshipsList";
        }
        model.addAttribute("method", "put");
        return "championships/groupChampionships";
    }

    @RequestMapping("/exportGroupChampionship/{ID}")
    @ResponseBody
    public void exportGroupChampionship(@PathVariable Integer ID) throws IOException {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = null;
        if (attr != null) {
            response = attr.getResponse();
        }
        GroupChampionship groupChampionship = groupChampionshipService.getGroupChampionshipByID(ID);
        ExcelUtil excelUtil = new ExcelUtil();
        if (response != null) {
            excelUtil.exportForGroup(response, groupChampionship);
        }
    }
}
